<template>
  <div>
    <t-card class="list-card-container">
      <t-row justify="space-between">
        <div class="left-operation-container">
          <t-button @click="refresh" theme="default" variant="outline"><template #icon><RefreshIcon/></template>  刷新</t-button>
          <t-button @click="openEdit('')" theme="primary" variant="outline"><template #icon><AddIcon/></template> 新增</t-button>
          <p v-if="!!selectedRowKeys.length" class="selected-count">已选{{ selectedRowKeys.length }}项</p>
        </div>
        <div class="search-input">
          <t-space>
            <t-date-range-picker allow-input clearable @pick="onPick" @change="onPickChange" />
            <t-input v-model="searchKey" placeholder="请输入你需要搜索的内容" clearable>
              <template #suffix-icon>
                <search-icon size="20px" />
              </template>
            </t-input>
          </t-space>
        </div>
      </t-row>

      <t-table :data="data" :columns="DRAFTS_COLUMNS" row-key="id" vertical-align="top" :hover="true"
        :pagination="pagination" :loading="dataLoading" :selected-row-keys="selectedRowKeys"
        @page-change="rehandlePageChange" @select-change="rehandleSelectChange">
        <template #status="{ row }">
          <t-tag v-if="row.status === 'draft'" theme="default" variant="light"> {{$t('pages.listBase.draft')}} </t-tag>
          <t-tag v-if="row.status === 'scheduled'" theme="warning" variant="light"> {{$t('pages.listBase.schedule')}} </t-tag>
          <t-tag v-if="row.status === 'published'" theme="success" variant="light"> {{$t('pages.listBase.publish')}} </t-tag>
        </template>
        <template #created_at="{row}">
          {{ dayjs(row.created_at).format('YYYY-MM-DD HH:mm:ss')}}
        </template>
        <template #op="slotProps">
          <a class="t-button-link" @click="openEdit(slotProps.row.id)">编辑</a>
        </template>
      </t-table>
    </t-card>

  </div>
</template>

<script type="ts">
export default {
  name: 'PostsDraft',
};
</script>
<script setup type="ts">
import { ref,reactive,onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { SearchIcon,RefreshIcon,AddIcon } from 'tdesign-icons-vue-next';
import { MessagePlugin } from 'tdesign-vue-next';

import { DRAFTS_COLUMNS } from './constants';

import { useLocale } from '@/locales/useLocale';
import dayjs from 'dayjs'
import { getAllPosts, savePosts,deletePosts,getPosts } from '@/api/posts';


const { locale } = useLocale();
const searchKey = ref('');
const router=useRouter();
const data = ref([]);
const pagination = reactive({
  current: 1,
  pageSize: 20,
  total: 0,
});
const dataLoading = ref(false);
const selectedRowKeys = ref([]);

const fetchData = async (d) => {
  dataLoading.value = true;
  try {
    const {items,totalItems,currentPage}=await getAllPosts(d);
    data.value = items;
    pagination.total = totalItems;
    pagination.current = currentPage;
  } catch (e) {
    if (e.message) {
      MessagePlugin.error(e.message);
    } else {
      MessagePlugin.error(e.msg);
    }
  } finally {
    dataLoading.value = false;
  }
};
// 刷新数据
const refresh = async () => {
  pagination.current = 1;
  await fetchData(pagination);
};

const rehandlePageChange = (pageInfo) => {
  console.log(`rehandlePageChange${JSON.stringify(pageInfo)}`);
  pagination.current = pageInfo.current;
  pagination.pageSize = pageInfo.pageSize;
  fetchData(pageInfo);
};

const rehandleSelectChange = (val) => {
  selectedRowKeys.value = val;
};

const openEdit=(id)=>{
  const params={id:id}
  router.push({
    name:'postsEdit',
    params:{id:id}
  })
}


onMounted(async () => {
  await fetchData({
    current: pagination.current,
    pageSize: pagination.pageSize,
  });

});


// 日期选择
const onPick = (value, context) => console.log('onPick:', value, context);
const onPickChange = (value, context) => {
  console.log('onPickChange:', value, context);
  console.log(
    'timestamp:',
    context.dayjsValue.map((d) => d.valueOf()),
  );
  console.log(
    'YYYYMMDD:',
    context.dayjsValue.map((d) => d.format('YYYYMMDD'))
  );

   fetchData({
    current: pagination.current,
    pageSize: pagination.pageSize,
    date:`${value[0],value[1]}`
  });
};

</script>

<style lang="less" scoped>

</style>
